package util

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"time"
)

type SessKey struct {
	OpenId     string `json:"open_id" form:"open_id"`
	SessionKey string `json:"session_key" form:"session_key"`
	UnionId    string `json:"union_id" form:"union_id"`
	ErrCode    int    `json:"err_code" form:"err_code"`
	ErrMsg     string `json:"err_msg" form:"err_msg"`
}

type WechatUser struct {
	OpenId    string `json:"openid" form:"open_id"`
	UnionId   string `json:"unionid" form:"union_id"`
	AvatarURL string `json:"avatarUrl" form:"avatar_url"`
	City      string `json:"city" form:"city"`
	Country   string `json:"country" form:"country"`
	Gender    int    `json:"gender" form:"gender"`
	Language  string `json:"language" form:"language"`
	NickName  string `json:"nickName" form:"nick_name"`
	Province  string `json:"province" form:"province"`
}

// https://www.w3cschool.cn/weixinapp/weixinapp-api-login.html
func GetWechatSessKey(appId, secret, code string) (sess *SessKey, err error) {
	// 微信小程序app登陆 URL
	api := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, secret, code)
	resp, err := httplib.Get(api).SetTimeout(60*time.Second, 60*time.Second).SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).String()
	if err != nil {
		return nil, err
	}
	json.Unmarshal([]byte(resp), sess)
	return sess, nil
}
